package cn.xchats.onlinetraffic.webapp.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/*
 *权限控制器
 *@author teddy
 *@date 2018/5/3
 */
@Component
public class PermissionInterceptor implements Filter {

    String controllerCheckString = "/v1.0/";

    private static final String[] sessionWhiteList = {"login","addSession","session","index","consumerDocument",
                                                                "producerDocument","why-use-document","err","register"};

    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(PermissionInterceptor.class);

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        try {
            //设置首页
            if (("/").equals(requestURI)) {
                request.getRequestDispatcher(controllerCheckString).forward(servletRequest, servletResponse);
                //response.sendRedirect(controllerCheckString);
                //chain.doFilter(servletRequest, servletResponse);
                return;
            }

            //session白名单
            for (int i = 0; i < sessionWhiteList.length; i++) {
                StringBuffer buffer = new StringBuffer();
                buffer.append(controllerCheckString).append(sessionWhiteList[i]);
                if (requestURI.equals(buffer.toString())) {
                    chain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }

            //除了控制器的请求，都放行
            if (!requestURI.contains(controllerCheckString)) {
                chain.doFilter(servletRequest, servletResponse);
                return;
            }

            HttpSession session = request.getSession(true);
            Object user = session.getAttribute("user");
            if (user == null) {
                System.out.println("未登录>>>" + requestURI);
                response.sendRedirect(controllerCheckString + "login");
                return;
            }

            chain.doFilter(servletRequest, servletResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}